import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:untitled/utils/common_toast.dart';
import 'package:untitled/utils/dio_http.dart';
import 'package:untitled/utils/scopoed_model_helper.dart';
import 'package:untitled/utils/store.dart';
import 'package:untitled/utils/string_is_null_or_empty.dart';
import 'package:untitled/widgets/page_content.dart';

import '../routes.dart';
import '../scoped_model/AuthModel.dart';
class LoginPage extends StatefulWidget {
  const LoginPage({Key key}) : super(key: key);

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  bool showPassword = false;//要赋初始值

  var usernameController = TextEditingController();
  var passwordController = TextEditingController();

  _loginHandle() async{
    var username = usernameController.text;
    var password = passwordController.text;
    if(stringIsNullOrEmpty(username) || stringIsNullOrEmpty(password)){
      CommonToast.showToast("用户名或密码不能为空！");
    }
    const url = '/user/login';
    var params = {
      'username':username,
      'password':password
    };
    var res = await DioHttp.of(context).post(url,params);
    var resMap = json.decode(res.toString());
    int status = resMap['status'];
    String description = resMap['description']??'内部错误';
    CommonToast.showToast(description);
    if(status == 220){
      String token = resMap['body']['token'];
      Store store = await Store.getInstance();
      await store.setString(StoreKeys.token, token);
      ScopedModelHelper.getModel<AuthModel>(context).login(token, context);

      //一秒之后回到上一个页面
      Timer(Duration(seconds: 1),(){
        Navigator.of(context).pop();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('登录'),
      ),
      body: SafeArea(//安全区域（内容区域），相当于给里面的内容添加一个外边距
        minimum: EdgeInsets.all(20),//上下左右边距为20
        child: ListView(//不用Column是怕软键盘弹出遮挡控件
          children: [
            TextField(
              decoration: InputDecoration(labelText: '账号', hintText: '请输入账号'),
            ),
            SizedBox(height: 10,),
            TextField(
              obscureText: !showPassword, //密码密文显示
              decoration: InputDecoration(
                  labelText: '密码',
                  hintText: '请输入密码',
                  suffixIcon: IconButton(icon:Icon(showPassword?Icons.visibility:Icons.visibility_off),
                    onPressed: (){
                      setState(() {
                        showPassword = !showPassword;
                      });
                    },
                  )//文本输入框尾部添加图标
              ),
            ),
            SizedBox(height: 20,),
            ElevatedButton(

                onPressed: () {
                  _loginHandle();
                },
                child: Text('登录'),
                style: ElevatedButton.styleFrom(
                  primary: Colors.green,//背景色
                  onPrimary: Colors.white//前景色
                ),
            ),
            SizedBox(height: 10,),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text('还没有账号？'),
                TextButton(
                  child: Text('去注册',style: TextStyle(color: Colors.green),),
                  onPressed: (){
                    //替换页面 使用pushName()是重新新建一个页面放在之前页面前面
                    Navigator.pushReplacementNamed(context, Routes.register);
                  },
                )
              ],
            )
          ],
        ),
      )

    );
  }
}


